package cn.wawi.utils;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.github.pagehelper.PageHelper;
import com.liang.kit.ReflectUtil;

/**
 * @description 查询工具类
 * @author 龚亮
 * @date 2014-10-18 12:21:34
 */
public class QueryUtil{

	private static final Integer PAGE_SIZE=10;         //默认每页显示10条数据
	private static final Integer PAGE_INDEX=1;         //默认当前页为第一页
	/**
	 * 通过request构造查询Map模型
	 * @param request 注意数组只能取第一个
	 * @return
	 */
	public static Map<String,Object> setPage(HttpServletRequest request){
		Map<String,Object> map=getMap(request);
		PageHelper.startPage(toPageIndex(map),toPageSize(map));     //设置分页
		return map;
	}
	/**
	 * 通过request构造查询Map模型,自定义分页
	 * @param request 注意数组只能取第一个
	 * @param pageIndex  当前页
	 * @param pageSize   每页显示多少条数据
	 * @return
	 */
	public static Map<String,Object> setPage(HttpServletRequest request,int pageIndex,int pageSize){
		PageHelper.startPage(pageIndex,pageSize);     //设置分页
		return getMap(request);
	}
	/**
	 * 通过request构造查询Map模型,不分页
	 * @param request 注意数组只能取第一个
	 * @return
	 */
	public static Map<String,Object> setNoPage(HttpServletRequest request){
		return getMap(request);
	}
	
	@SuppressWarnings("all")
	public static Map<String,Object> getMap(HttpServletRequest request){
		Map<String,Object> map=new HashMap<String,Object>();
		Enumeration names=request.getParameterNames();
		while(names.hasMoreElements()){
		   String name=(String) names.nextElement();
		   String value=request.getParameter(name);
		   if(null!=value&&!"".equals(value.trim())){//过滤空值或空字符串
			   map.put(name, value.trim());
		   }
		}
		return map;
	}
	/**
	 * 字符串转pageIndex
	 */
	public static Integer toPageIndex(Map<String,Object> map) {
		String pageIndex=(String) (map.containsKey("page")?map.get("page"):map.get("pageIndex"));
		if (null == pageIndex || "".equals(pageIndex.trim())) {
			return PAGE_INDEX;
		} else {
			return Integer.parseInt(pageIndex);
		}
	}
	/**
	 * 字符串转pageSize
	 */
	public static Integer toPageSize(Map<String,Object> map) {
		String pageSize=(String) (map.containsKey("rows")?map.get("rows"):map.get("pageSize"));
		if (null == pageSize || "".equals(pageSize.trim())) {
			return PAGE_SIZE;
		} else {
			return Integer.parseInt(pageSize);
		}
	}
	public static Object initModel(HttpServletRequest request,Class<?> clazz){
		Map<String,Object> map=getMap(request);
		if(map.containsKey("password")){
			map.put("password", StringEscapeUtil.md5(map.get("password").toString()));
		}
		return ReflectUtil.populate(map, clazz);
	}
}
